package com.library.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.json.JSONObject;
import com.library.util.DBUtil;

@WebServlet("/cancelSubscription")
public class CancelSubscriptionServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        JSONObject jsonResponse = new JSONObject();

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("userId") == null) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "请先登录");
            response.getWriter().write(jsonResponse.toString());
            return;
        }
        int userId = (int) session.getAttribute("userId");
        int borrowId;
        int bookId;
        try {
            borrowId = Integer.parseInt(request.getParameter("borrowId"));
            bookId = Integer.parseInt(request.getParameter("bookId"));
        } catch (Exception e) {
            jsonResponse.put("success", false);
            jsonResponse.put("message", "参数错误");
            response.getWriter().write(jsonResponse.toString());
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            // 更新借阅记录状态为已归还
            String updateStatusSql = "UPDATE borrow_records SET status = 'returned', return_date = NOW() WHERE id = ? AND user_id = ?";
            try (PreparedStatement updateStmt = conn.prepareStatement(updateStatusSql)) {
                updateStmt.setInt(1, borrowId);
                updateStmt.setInt(2, userId);
                int affected = updateStmt.executeUpdate();
                if (affected == 0) {
                    jsonResponse.put("success", false);
                    jsonResponse.put("message", "操作失败");
                    response.getWriter().write(jsonResponse.toString());
                    return;
                }
            }
            // 恢复图书可借数量
            String updateBookSql = "UPDATE books SET available_copies = available_copies + 1 WHERE id = ?";
            try (PreparedStatement updateBookStmt = conn.prepareStatement(updateBookSql)) {
                updateBookStmt.setInt(1, bookId);
                updateBookStmt.executeUpdate();
            }
            jsonResponse.put("success", true);
            jsonResponse.put("message", "取消订阅成功");
        } catch (SQLException e) {
            e.printStackTrace();
            jsonResponse.put("success", false);
            jsonResponse.put("message", "系统错误");
        }
        response.getWriter().write(jsonResponse.toString());
    }
}